package com.daocao.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.daocao.common.constants.CacheConstants;
import com.daocao.common.domain.vo.LoginUserVO;
import com.daocao.common.utils.redis.RedisCacheUtil;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JwtUtils {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    private String secret = "jjfksuefiesiowjfowjfow";
    /**
     * 创建Token，会将用户数据存放到redis中
     */
    public String createToken(LoginUserVO loginUserVO){
        //UmsSysUser sysUser = loginUserVO.getSysUser();
        
        //创建一个map
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //将UUID存储到登录用户中
        loginUserVO.setToken(token);
        //设置登录时间
        loginUserVO.setLoginTime(System.currentTimeMillis());
        Map<String, Object> claims = new HashMap<>();
        claims.put("token", token);
//        claims.put("id", sysUser.getId());
//        claims.put("username", sysUser.getUsername());
//        claims.put("nickname", sysUser.getNickname());
//        claims.put("avatar", sysUser.getAvatar());
        //将用户数据缓存到redis中
        redisCacheUtil.setCacheObject(CacheConstants.LOGIN_USER_KEY+token, loginUserVO,30,TimeUnit.MINUTES);
        return Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
    }

     /**
      * 解析Token
      */

      public Claims parseToken(String token){
        //解析token
        return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

      }
      /**
       * 获取登录用户
       * 根据Token，解析之后redis中的数据
       * 并且刷新token
       */
      public Object getLoginUser(HttpServletRequest request){
        //通过Jwt加密过的
        String token = request.getHeader("Daocao-Authorization");

        if(StrUtil.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            log.info("claims=======>{}", claims);
            String parsseToken = (String)claims.get("token");
            log.info("parsseToken=======>{}", parsseToken);
            //从redis中获取
            LoginUserVO loginUserVO = redisCacheUtil.getCacheObject(CacheConstants.LOGIN_USER_KEY + parsseToken);
            // 获取登录时间
            long loginTime = loginUserVO.getLoginTime();
            // 获取当前时间
            long currentTimeMillis = System.currentTimeMillis();
            // 判断是否相差20分钟
            long millis = currentTimeMillis / 1000 / 60 - loginTime/ 1000 / 60;
            if(millis >= 20) {
                refreshToken(loginUserVO);
            }
            return loginUserVO;
        }
        return null;
      }

    // 刷新token
    private void refreshToken(LoginUserVO loginUserVO) {
        // 将用户数据缓存到redis中
        redisCacheUtil.setCacheObject(CacheConstants.LOGIN_USER_KEY + loginUserVO.getToken(),loginUserVO,30, TimeUnit.MINUTES);
    }
}
